#include <QDebug>
#include <QSqlQuery>
#include <QSqlError>
#include <QColorDialog>
#include "producteditdialog.h"
#include "ui_producteditdialog.h"

ProductEditDialog::ProductEditDialog(QWidget *parent, QSqlDatabase db, int id)
    : QDialog(parent)
    , ui(new Ui::ProductEditDialog)
    , db_(db)
    , id_(id)
{
    ui->setupUi(this);

    initializeClientList();
    initializeTaskList();

    QString q = QString(
                    "select p.name, p.orderno, p.start, p.end, p.closed, c.id, cl.id, pc.color "
                    "from product as p, clientusers as cl, company as c "
                    "left join PRODUCTCOLOR as pc "
                    "on p.id=pc.prodid "
                    "where p.clientid=cl.id and cl.companyid=c.id and p.id='%1'").arg(id_);
    QSqlQuery query = db_.exec(q);
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        return;
    }

    if (query.next()) {
        ui->productNameLineEdit->setText( query.value(0).toString() );
        ui->orderNumberLineEdit->setText( query.value(1).toString() );
        ui->startDateEdit->setDate( query.value(2).toDate() );
        ui->endDateEdit->setDate( query.value(3).toDate() );
        ui->closedCheckBox->setChecked( query.value(4).toBool() );

        for (int i=0; i<ui->clientCompanyComboBox->count(); ++i) {
            int companyID = ui->clientCompanyComboBox->itemData(i).toInt();
            if (companyID == query.value(5).toInt()) {
                ui->clientCompanyComboBox->setCurrentIndex(i);
                break;
            }
        }

        for (int i=0; i<ui->clientUsersComboBox->count(); ++i) {
            int userID = ui->clientUsersComboBox->itemData(i).toInt();
            if (userID == query.value(6).toInt()) {
                ui->clientUsersComboBox->setCurrentIndex(i);
                break;
            }
        }

        if (!query.value(7).isNull()) {
            color_ = QColor(query.value(7).toUInt());
            ui->colorButton->setStyleSheet( QString("background-color:rgb(%1, %2, %3)").arg(color_.red()).arg(color_.green()).arg(color_.blue()) );
        }
    }
    else {
        QDate today = QDate::currentDate();
        QDate beg = QDate(today.year(), today.month(), 1);
        ui->startDateEdit->setDate(beg);
        ui->endDateEdit->setDate(beg.addMonths(1).addDays(-1));
    }
}

ProductEditDialog::~ProductEditDialog()
{
    delete ui;
}

void ProductEditDialog::accept()
{
    QDialog::accept();

    QString name = ui->productNameLineEdit->text();
    QString orderno = ui->orderNumberLineEdit->text();
    int clientid = ui->clientUsersComboBox->itemData( ui->clientUsersComboBox->currentIndex() ).toInt();
    QString start = ui->startDateEdit->date().toString(Qt::ISODate);
    QString end = ui->endDateEdit->date().toString(Qt::ISODate);
    bool closed = ui->closedCheckBox->isChecked();

    db_.exec("BEGIN IMMEDIATE");

    // insert or update product table
    QString q;
    if (id_ == 0) {
        q = QString("insert into PRODUCT"
                    "(name, orderno, clientid, start, end, closed)"
                    " values('%1', '%2', %3, '%4', '%5', %6)")
                    .arg(name).arg(orderno).arg(clientid).arg(start).arg(end).arg(closed);
    }
    else {
        q = QString("update PRODUCT set"
                    " name='%1', orderno='%2', clientid=%3, start='%4', end='%5', closed=%6"
                    " where id=%7")
                    .arg(name).arg(orderno).arg(clientid).arg(start).arg(end).arg(closed).arg(id_);
    }

    QSqlQuery query = db_.exec(q);
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        db_.exec("ROLLBACK");
        return;
    }

    // if this product is new product, get created product id
    int prodid = id_;
    if (prodid == 0) {
        query = db_.exec("select max(id), max(sortorder)+1 from PRODUCT");
        if (query.lastError().isValid()) {
            qDebug() << query.lastError().text();
            db_.exec("ROLLBACK");
            return;
        }
        query.next();
        prodid = query.value(0).toInt();
        int sortorder = query.value(1).toInt();
        query = db_.exec( QString("update PRODUCT set sortorder=%1 where id=%2").arg(sortorder).arg(prodid) );
    }

    // update task
    query = db_.exec( QString("delete from PRODUCTTASK where prodid=%1").arg(prodid) );
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        db_.exec("ROLLBACK");
        return;
    }

    QList<QListWidgetItem*> items = ui->taskListWidget->selectedItems();
    foreach(QListWidgetItem* i, items) {
        int cateid = i->data(Qt::UserRole).toInt();
        q = QString("insert into PRODUCTTASK(prodid, cateid) values(%1, %2)").arg(prodid).arg(cateid);
        query = db_.exec(q);
        if (query.lastError().isValid()) {
            qDebug() << query.lastError().text();
            db_.exec("ROLLBACK");
            return;
        }
    }

    if (color_.isValid()) {
        query = db_.exec( QString("select count(*) from PRODUCTCOLOR where prodid=%1").arg(prodid) );
        if (query.lastError().isValid()) {
            qDebug() << "failure";
            qDebug() << query.lastError().text();
            db_.exec("ROLLBACK");
            return;
        }

        query.next();
        if(query.value(0).toInt() > 0)
            query = db_.exec( QString("update PRODUCTCOLOR set color=%1 where prodid=%2").arg(color_.rgb()).arg(prodid) );
        else
            query = db_.exec( QString("insert into PRODUCTCOLOR(prodid, color) values(%1, %2)").arg(prodid).arg(color_.rgb()) );

        if (query.lastError().isValid()) {
            qDebug() << query.lastError().text();
            db_.exec("ROLLBACK");
            return;
        }
    }
    else
        query = db_.exec( QString("delete from PRODUCTCOLOR where prodid=%1").arg(prodid) );

    db_.exec("COMMIT");
}

void ProductEditDialog::initializeClientList()
{
    QSqlQuery query = db_.exec("select * from COMPANY");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        return;
    }

    while (query.next()) {
        int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        ui->clientCompanyComboBox->addItem(name, id);
    }
}

void ProductEditDialog::initializeTaskList()
{
    // add all tasks to list widget
    QSqlQuery query = db_.exec("select * from TASKCATEGORY order by id");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        return;
    }

    // task id 1 to 11 are selected from the first.
    int i = 0;
    while (query.next()) {
        int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        QListWidgetItem* item = new QListWidgetItem(name, ui->taskListWidget);
        item->setData(Qt::UserRole, id);
        if (id_ == 0 && i < 11)
            ui->taskListWidget->setCurrentItem(item);
        ++i;
    }

    // select current tasks if editing existing product.
    if (i != 0) {
        QString q = QString("select * from PRODUCTTASK where prodid=%1").arg(id_);
        query = db_.exec(q);
        if (query.lastError().isValid()) {
            qDebug() << query.lastError().text();
            return;
        }

        while (query.next()) {
            int cateID = query.value(2).toInt();
            for (int i=0; i<ui->taskListWidget->count(); ++i) {
                QListWidgetItem* item = ui->taskListWidget->item(i);
                if (cateID == item->data(Qt::UserRole).toInt()) {
                    item->setSelected(true);
                    break;
                }
            }
        }
    }
}

void ProductEditDialog::on_clientCompanyComboBox_currentIndexChanged(int index)
{
    ui->clientUsersComboBox->clear();

    int companyID = ui->clientCompanyComboBox->itemData(index).toInt();

    QSqlQuery query = db_.exec( QString("select * from CLIENTUSERS where companyID='%1'").arg(companyID) );
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        return;
    }

    while (query.next()) {
        int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        ui->clientUsersComboBox->addItem(name, id);
    }
}

void ProductEditDialog::on_colorButton_clicked()
{
    QColor color = QColorDialog::getColor(color_, this);
    if (!color.isValid())
        return;
    color_ = color;
    ui->colorButton->setStyleSheet( QString("background-color:rgb(%1, %2, %3)").arg(color.red()).arg(color.green()).arg(color.blue()) );
}
